package com.example.bishetianqi;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.bishetianqi.base.BaseFragment;
import com.example.bishetianqi.bean.WeatherBean;
import com.example.bishetianqi.db.DBManager;
import com.example.bishetianqi.unti.Httputil;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class CityWeatherFragment extends BaseFragment {

    TextView title_city,quality_text,pm25_text,now_currenttemp,now_condition,now_date,now_wind,now_temprange,cloth_text,wash_car_text,ganmaotext,sport_text,uv_text;
    SwipeRefreshLayout swipeRefreshLayout;
    LinearLayout futureLayout;
    String city;
    String url1="http://api.map.baidu.com/telematics/v3/weather?location=";
    String url2="&output=json&ak=FkPhtMBK0HTIQNh7gG4cNUttSTyr0nzo";
    private List<WeatherBean.ResultsBean.IndexBean> indexLists;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_city_weather, container, false);
        initview(view);
        //通过Activity来获取加载的城市天气情况
        Bundle bundle=getArguments();
        city=bundle.getString("city");
        final String url=url1+city+url2;
        //final String urltest=url1+"北京"+url2;
        loadData(url);
        updateBingPic();

        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               // loadData(urltest);
                loadData(url);
                updateBingPic();
            }
        });

        return view;
    }

    @Override
    public void onSuccess(String result) {
        //解析并展示数据
        showData(result);
        //更新数据
        int i=DBManager.updateInfoByCity(city,result);
        if (i<=0){
            //更新失败，此城市不在数据库中，增加该条记录
            DBManager.addcityInfo(city,result);
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        super.onError(ex, isOnCallback);
        //更新失败，查询上次信息并展示
        String s=DBManager.queryInfoByCity(city);
        if (!TextUtils.isEmpty(s)){
            showData(s);
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    private void showData(String result) {

        WeatherBean weatherBean=new Gson().fromJson(result,WeatherBean.class);
        WeatherBean.ResultsBean resultsBean=weatherBean.getResults().get(0);
        indexLists = resultsBean.getIndex();
        //设置Textview数据
        title_city.setText(resultsBean.getCurrentCity());
        pm25_text.setText(resultsBean.getPm25());
        int pm25= Integer.parseInt(resultsBean.getPm25());
        if (pm25>0&&pm25<50){
            quality_text.setText("优");
        }else if (pm25>51&&pm25<100){
            quality_text.setText("良");
        }else if (pm25>51&&pm25<100){
            quality_text.setText("良");
        }else if (pm25>101&&pm25<150){
            quality_text.setText("轻度污染");
        }else if (pm25>151&&pm25<200){
            quality_text.setText("中度污染");
        }else if (pm25>201&&pm25<300){
            quality_text.setText("重度污染");
        }else if (pm25>300){
            quality_text.setText("严重污染");
        }
        WeatherBean.ResultsBean.WeatherDataBean weatheroftodayBean = resultsBean.getWeather_data().get(0);
        //需对返回的数据进行处理，以便获取当日气温（周三 04月01日 (实时：13℃)）
        String[] split=weatheroftodayBean.getDate().split("：");
        String todaytemp = split[1].replace(")", "");
        now_currenttemp.setText(todaytemp);
        now_date.setText(weatherBean.getDate());
        now_condition.setText(weatheroftodayBean.getWeather());
        now_wind.setText(weatheroftodayBean.getWind());
        now_temprange.setText(weatheroftodayBean.getTemperature());
        //获取生活建议
        String clothtip=indexLists.get(0).getZs()+","+indexLists.get(0).getDes();
        String washcartip=indexLists.get(1).getZs()+","+indexLists.get(1).getDes();
        String ganmaotip=indexLists.get(2).getZs()+","+indexLists.get(2).getDes();
        String sporttip=indexLists.get(3).getZs()+","+indexLists.get(3).getDes();
        String uvtip=indexLists.get(4).getZs()+","+indexLists.get(4).getDes();
        cloth_text.setText(clothtip);
        wash_car_text.setText(washcartip);
        ganmaotext.setText(ganmaotip);
        sport_text.setText(sporttip);
        uv_text.setText(uvtip);
        //设置图片
         //Picasso.with(getActivity()).load(weatheroftodayBean.getDayPictureUrl()).into(now_weather_icon);
        //获取未来三天的天气情况
        List<WeatherBean.ResultsBean.WeatherDataBean> frtureList = resultsBean.getWeather_data();
        frtureList.remove(0);
        futureLayout.removeAllViews();
        for (int i=0;i<frtureList.size();i++){
            View itemview=LayoutInflater.from(getActivity()).inflate(R.layout.forecast_item,null);
            itemview.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            TextView maxtemp=itemview.findViewById(R.id.item_max_temp);
            TextView mintemp=itemview.findViewById(R.id.item_min_temp);
            TextView itemdata=itemview.findViewById(R.id.item_date);
            TextView itemcondition=itemview.findViewById(R.id.item_condition);
            ImageView itemicon=itemview.findViewById(R.id.item_icon);
            //获取未来的天气情况
            WeatherBean.ResultsBean.WeatherDataBean nextonedatabean = frtureList.get(i);
            itemdata.setText(nextonedatabean.getDate());
            itemcondition.setText(nextonedatabean.getWeather());
            //处理数据
            String test=nextonedatabean.getTemperature();
            String max,min,zhongjian;
            String[] spilt=test.split("~");
            max=spilt[0];
            zhongjian=spilt[1];
            String[] strings=zhongjian.split("℃");
            min=strings[0];
            maxtemp.setText(max);
            mintemp.setText(min);
            Picasso.with(getActivity()).load(nextonedatabean.getDayPictureUrl()).into(itemicon);
            futureLayout.addView(itemview);
        }
    }

    private void initview(View view) {
        title_city=view.findViewById(R.id.title_city);
        quality_text=view.findViewById(R.id.quality_text);
        pm25_text=view.findViewById(R.id.pm25_text);
        now_currenttemp=view.findViewById(R.id.now_currenttemp);
        now_condition=view.findViewById(R.id.now_condition);
        now_date=view.findViewById(R.id.now_date);
        now_wind=view.findViewById(R.id.now_wind);
        now_temprange=view.findViewById(R.id.now_temprange);
        cloth_text=view.findViewById(R.id.cloth_text);
        wash_car_text=view.findViewById(R.id.wash_car_text);
        ganmaotext=view.findViewById(R.id.ganmaotext);
        sport_text=view.findViewById(R.id.sport_text);
        uv_text=view.findViewById(R.id.uv_text);
        futureLayout=view.findViewById(R.id.forecast_layout);
        swipeRefreshLayout=view.findViewById(R.id.swipe);
    }

    private void updateBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        Httputil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

}
